<?php
/**
 User: Mykola B.
 * Date: 3/1/13
 * Time: 7:52 PM
 */
namespace models {
    class BaseModel
    {
        protected $db;
        public $mapper;

        // used with late static binding
        protected static $fields = array();

        public function __construct($tableName) {
            $this->db = \DataBase::getConnection()->link;
            $this->mapper = new \DB\SQL\Mapper($this->db, $tableName);
        }

        public function all() {
            return $this->mapper->find();
        }

        /**
         * If property is in model fields assign it to the mapper.
         * @param $name
         * @param $value
         */
        public function __set($name, $value) {
            if (in_array($name, static::$fields)) {
                $this->mapper->$name = $value;
            }
        }

        /**
         * If property is in model fields try to
         * @param $name
         * @return null
         */
        public function __get($name) {
            if (in_array($name, static::$fields) && isset($this->mapper->$name)) {
                return $this->mapper->$name;
            }
            return null;
        }

        /**
         * Let the \DB\SQL\Mapper handle calls to non-existing methods.
         * @param $method
         * @param $args
         */
        public function __call($method, $args) {
            if (is_callable(array($this->mapper, $method), true)) {
                return call_user_func_array(array($this->mapper, $method), $args);
            }
        }

    }
}
